// JavaScript Document
$(document).ready(function(e) {
	$("select[name='function']").change(function(){
		$("select[name='subfunction'] > option:gt(0)").remove(); 
		var html = "";
		$.each(subfunction[$(this).val()]['child'], function(i, n){
			html += "<option value='"+i+"'>"+n+"</option>";
		});
		$("select[name='subfunction']").append(html);
	});
	
	// 部门JSON
	var deptHtml = "<div class=\"form-group item\">"+
		"<label class=\"col-md-2 control-label\"></label>"+
		"<div class=\"col-md-6\">"+
			"<select name=\"department_id[]\" class=\"form-control\">"+
				"<option value=\"\"></option>";
	$.each(deptJson, function(i, n){
		deptHtml += "<option value='"+n.id+"'>"+n.department_name+"</option>";
	});
	deptHtml += "</select></div></div>";
	
	// 点击添加一行
	$(".add_line").click(function(){
		$(".item:last").after(deptHtml);
		$(".item:last").find(".control-label").html($(".item").length - 1);
	});
	
	// 点击保存按钮
	$(".clickBtn").click(function(){
		$(".tips_error").remove();
		if($("select[name='function']").val() == ""){
			$(".form-actions").append("<span class=\"tips_error\">功能模块不允许为空！</span>");
			$("select[name='function']").focus()
			return false;
		}
		if($("select[name='subfunction']").val() == ""){
			$(".form-actions").append("<span class=\"tips_error\">子功能模块不允许为空！</span>");
			$("select[name='subfunction']").focus()
			return false;
		}
		if($(".item").length == 1){
			$(".form-actions").append("<span class=\"tips_error\">请选择流程单位！</span>");
			return false;
		}
		var check = false;
		$(".item").each(function(index, element) {
			if(index == 0){
				return true;
			}
			if($(this).find("select[name=\"department_id[]\"]").val() == ""){
				check = true;
				$(".form-actions").append("<span class=\"tips_error\">第"+index+"行流程部门不允许为空！</span>");
				return false;
			}
		});
		if(check){
			return false;
		}
		
		$(".item").each(function(index, element) {
			if(index == 0){
				return true;
			}
			var selectVal = $(this).find("select[name=\"department_id[]\"]").val();
			$(".item:gt("+index+")").each(function(i, element) {
				if($(this).find("select[name=\"department_id[]\"]").val() == selectVal){
					check = true;
					$(".form-actions").append("<span class=\"tips_error\">第"+index+"行与第"+(index + 1 + i)+"行流程部门重复！</span>");
					return false;
				}
				if(check){
					return false;
				}
			});
			if(check){
				return true;
			}
		});
		if(check){
			return false;
		}
		
		// 表单提交
		$("form").submit();
	});
});